package com.type.TypingDetector;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import android.view.GestureDetector.OnGestureListener; 
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class GestureRecognition extends Activity implements OnGestureListener {
  public static final String TYPE = "type";
  private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
  private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
  private XYSeries mCurrentSeries;
  private XYSeriesRenderer mCurrentRenderer;
  private String mDateFormat;
  private GraphicalView mChartView;
  private SensorManager sm;
  private List<Sensor> sensors;
  private Sensor accel;
  private long time;
  private boolean first=true;
  private int ctr;
  private GestureDetector mGestureScanner; 
  private Button bton;

  @Override
  protected void onRestoreInstanceState(Bundle savedState) {
    super.onRestoreInstanceState(savedState);
    mDataset = (XYMultipleSeriesDataset) savedState.getSerializable("dataset");
    mRenderer = (XYMultipleSeriesRenderer) savedState.getSerializable("renderer");
    mCurrentSeries = (XYSeries) savedState.getSerializable("current_series");
    mCurrentRenderer = (XYSeriesRenderer) savedState.getSerializable("current_renderer");
    mDateFormat = savedState.getString("date_format");
    //sm = (SensorManager) savedState.getSerializable("SensorManager");
    first=savedState.getBoolean("first");
    time=savedState.getLong("time");
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("dataset", mDataset);
    outState.putSerializable("renderer", mRenderer);
    outState.putSerializable("current_series", mCurrentSeries);
    outState.putSerializable("current_renderer", mCurrentRenderer);
    outState.putString("date_format", mDateFormat);
    outState.putLong("time", time);
    //outState.putSerializable(key, value);
    outState.putBoolean("first", first);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xy_chart);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    //this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
    Random generator=new Random(6);
    
    AssetManager am=getAssets();
    String[] seriesTitle = {"X Magnitudes", "Y Magnitudes", "Z Magnitudes"};
    int[] colors=new int[seriesTitle.length];
	for (int k=0; k<colors.length; k++) {
		colors[k]=Color.rgb(generator.nextInt(255), generator.nextInt(255), generator.nextInt(255));
	}
    for (int i=0; i<3; i++) {
    	XYSeries series = new XYSeries(seriesTitle[i]);
    	mDataset.addSeries(series);
    	XYSeriesRenderer renderer = new XYSeriesRenderer();
    	renderer.setLineWidth(2.0f);
    	renderer.setColor(colors[i]);
    	mRenderer.addSeriesRenderer(renderer);
    }
    
	mCurrentSeries=mDataset.getSeriesAt(0);
	mCurrentRenderer=(XYSeriesRenderer) mRenderer.getSeriesRendererAt(0);
	mGestureScanner = new GestureDetector(this); 
	bton=(Button)findViewById(R.id.gesButton);
	mRenderer.setXAxisMin(0);
	mRenderer.setXAxisMax(511);
	Intent in=new Intent();
	in.putExtra("startCounter", (int)mRenderer.getXAxisMin());
	in.putExtra("endCounter", (int)mRenderer.getXAxisMax());
	setResult(Activity.RESULT_OK,in);
	
	bton.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent i=new Intent();
			  i.putExtra("startCounter", (int)mRenderer.getXAxisMin());
			  i.putExtra("endCounter", (int)mRenderer.getXAxisMax());
			  setResult(Activity.RESULT_OK,i);
			finish();
		}
		
	});
	
	Intent temp=this.getIntent();
	Bundle b=temp.getExtras();
	double[] xVals=b.getDoubleArray("xVals");
	double[] yVals=b.getDoubleArray("yVals");
	double[] zVals=b.getDoubleArray("zVals");
	//boolean bAM=b.getBoolean("am");
	double[][] vals = {xVals, yVals, zVals};
	
	ctr=xVals.length;
	for (int i=0; i<mDataset.getSeriesCount(); i++) {
		mCurrentSeries=mDataset.getSeriesAt(i);
		mCurrentRenderer=(XYSeriesRenderer)mRenderer.getSeriesRendererAt(i);
		for (int j=0; j<vals[i].length; j++) {
			mCurrentSeries.add(j, vals[i][j]);
		}
	}
	if (mChartView != null) {
	       mChartView.repaint();
	}
	
    if(time==0) {time=SystemClock.uptimeMillis();}
 }

  
  @Override
  protected void onResume() {
    super.onResume();
    if (mChartView == null) {
      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
      mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
      layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
          LayoutParams.FILL_PARENT));
      //boolean enabled = mDataset.getSeriesCount() > 0;
      //setSeriesEnabled(enabled);
    } else {
      mChartView.repaint();
    }
  }
  
  @Override
  protected void onDestroy() {
	  Intent i=new Intent();
	  i.putExtra("startCounter", mRenderer.getXAxisMin());
	  i.putExtra("endCounter", mRenderer.getXAxisMax());
	  setResult(Activity.RESULT_OK,i);
	  super.onDestroy();
  }

@Override
public boolean onDown(MotionEvent e) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
		float velocityY) {
	// TODO Auto-generated method stub
		int nMin=(int)(mRenderer.getXAxisMin()+(-1*velocityX));
		if (nMin<0) nMin=0;
		int nMax=nMin+511;
		if (nMax>ctr) {
			nMax=ctr;
			nMin=ctr-511;
		}
		mRenderer.setXAxisMin(nMin);
		mRenderer.setXAxisMax(nMax);
		if (mChartView != null) {
			//int interval=(nMin-((int)mRenderer.getXAxisMin()))/5;
			/*if (nMin > (int)mRenderer.getXAxisMin()) {
				for (int i=(int)mRenderer.getXAxisMin(); i<nMin; i++) {
					int setNew;
					if (i>nMin)
						setNew=nMin;
					else
						setNew=i;
					mRenderer.setXAxisMin(setNew);
					mRenderer.setXAxisMax(setNew+512);
					mChartView.repaint();
					long time=SystemClock.uptimeMillis();
					long endTime=time+1000;
					while (time<endTime) {
						time=SystemClock.uptimeMillis();
					}
				}
			}
			else {
				for (int i=(int)mRenderer.getXAxisMin(); i>nMin; i--) {
					int setNew;
					if (i<nMin)
						setNew=nMin;
					else
						setNew=i;
					mRenderer.setXAxisMin(setNew);
					mRenderer.setXAxisMax(setNew+512);
					mChartView.repaint();
					long time=SystemClock.uptimeMillis();
					long endTime=time+1000;
					while (time<endTime) {
						time=SystemClock.uptimeMillis();
					}
				}
			}*/
			mChartView.repaint();
		}
	return true;
}

@Override
public void onLongPress(MotionEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
		float distanceY) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public void onShowPress(MotionEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public boolean onSingleTapUp(MotionEvent e) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean onTouchEvent(MotionEvent me) {
        return mGestureScanner.onTouchEvent(me);
} 
}
